package com.yic.module.mes.controller.admin.report;

import cn.hutool.core.util.ObjectUtil;
import com.yic.module.base.api.center.CenterApi;
import com.yic.module.base.api.center.dto.CenterRespDTO;
import com.yic.module.base.api.factory.FactoryApi;
import com.yic.module.base.api.factory.dto.FactoryRespDTO;
import com.yic.module.base.api.item.ItemApi;
import com.yic.module.base.api.item.dto.ItemRespDTO;
import com.yic.module.base.api.workshop.WorkshopApi;
import com.yic.module.base.api.workshop.dto.WorkshopRespDTO;
import com.yic.module.mes.dal.dataobject.plan.PlanDO;
import com.yic.module.mes.dal.dataobject.process.ProcessDO;
import com.yic.module.mes.service.plan.PlanService;
import com.yic.module.mes.service.process.ProcessService;
import com.yic.module.system.api.dept.DeptApi;
import com.yic.module.system.api.dept.dto.DeptRespDTO;
import com.yic.module.system.api.user.AdminUserApi;
import com.yic.module.system.api.user.dto.AdminUserRespDTO;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;

import com.yic.framework.common.pojo.PageResult;
import com.yic.framework.common.pojo.CommonResult;
import static com.yic.framework.common.pojo.CommonResult.success;

import com.yic.framework.excel.core.util.ExcelUtils;

import com.yic.framework.operatelog.core.annotations.OperateLog;
import static com.yic.framework.operatelog.core.enums.OperateTypeEnum.*;

import com.yic.module.mes.controller.admin.report.vo.*;
import com.yic.module.mes.dal.dataobject.report.ReportDO;
import com.yic.module.mes.convert.report.ReportConvert;
import com.yic.module.mes.service.report.ReportService;

@Tag(name = "管理后台 - 生产报工")
@RestController
@RequestMapping("/mes/report")
@Validated
public class ReportController {

    @Resource
    private ReportService reportService;
    @Resource
    private FactoryApi factoryApi;
    @Resource
    private WorkshopApi workshopApi;
    @Resource
    private DeptApi deptApi;
    @Resource
    private CenterApi centerApi;
    @Resource
    private ItemApi itemApi;
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private PlanService planService;
    @Resource
    private ProcessService processService;



    @PostMapping("/create")
    @Operation(summary = "创建生产报工")
    @PreAuthorize("@ss.hasPermission('mes:report:create')")
    public CommonResult<Boolean> createReport(@Valid @RequestBody ReportCreateReqVO createReqVO) {
        reportService.createReport(createReqVO);
        return success(true);
    }

    @PutMapping("/update")
    @Operation(summary = "更新生产报工")
    @PreAuthorize("@ss.hasPermission('mes:report:update')")
    public CommonResult<Boolean> updateReport(@Valid @RequestBody ReportUpdateReqVO updateReqVO) {
        reportService.updateReport(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除生产报工")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:report:delete')")
    public CommonResult<Boolean> deleteReport(@RequestParam("id") Long id) {
        reportService.deleteReport(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得生产报工")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:report:query')")
    public CommonResult<ReportRespVO> getReport(@RequestParam("id") Long id) {
        ReportDO report = reportService.getReport(id);
        return success(ReportConvert.INSTANCE.convert(report));
    }

    @GetMapping("/list")
    @Operation(summary = "获得生产报工列表")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    @PreAuthorize("@ss.hasPermission('mes:report:query')")
    public CommonResult<List<ReportRespVO>> getReportList(@RequestParam("ids") Collection<Long> ids) {
        List<ReportDO> list = reportService.getReportList(ids);
        return success(ReportConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @Operation(summary = "获得生产报工分页")
    @PreAuthorize("@ss.hasPermission('mes:report:query')")
    public CommonResult<PageResult<ReportRespVO>> getReportPage(@Valid ReportPageReqVO pageVO) {
        PageResult<ReportDO> pageResult = reportService.getReportPage(pageVO);
        PageResult<ReportRespVO> resp = ReportConvert.INSTANCE.convertPage(pageResult);
        resp.getList().forEach(tmp -> {
            // 封装工厂
            FactoryRespDTO factory = factoryApi.getFactory(tmp.getFactoryId());
            if (ObjectUtil.isNotEmpty(factory)) {
                tmp.setFactoryName(factory.getName());
            }
            // 封装生产车间
            WorkshopRespDTO workshop = workshopApi.getWorkshop(tmp.getWorkshopId());
            if (ObjectUtil.isNotEmpty(workshop)) {
                tmp.setWorkshopName(workshop.getName());
            }
            // 封装工作中心
            CenterRespDTO center = centerApi.getCenter(tmp.getCenterId());
            if (ObjectUtil.isNotEmpty(center)) {
                tmp.setCenterName(center.getName());
            }
            // 封装部门
            DeptRespDTO dept = deptApi.getDept(tmp.getDeptId());
            if (ObjectUtil.isNotEmpty(dept)) {
                tmp.setDeptName(dept.getName());
            }
            // 封装生产计划
            PlanDO plan = planService.getPlan(tmp.getPlanId());
            if (ObjectUtil.isNotEmpty(plan)) {
                tmp.setPlanCode(plan.getCode());
            }
            // 封装产品信息
            ItemRespDTO item = itemApi.getItem(tmp.getItemId());
            if (ObjectUtil.isNotEmpty(item)) {
                tmp.setItemName(item.getName());
                tmp.setItemCode(item.getCode());
                tmp.setSpec(item.getSpec());
                tmp.setDrawCode(item.getDrawCode());
            }
            // 封装报工人
            AdminUserRespDTO user = adminUserApi.getUser(tmp.getUserId());
            if (ObjectUtil.isNotEmpty(user)) {
                tmp.setUserName(user.getNickname());
            }
            // 封装工序
            ProcessDO process = processService.getProcess(tmp.getProcessId());
            if (ObjectUtil.isNotEmpty(process)) {
                tmp.setProcessName(process.getName());
            }
        });
        return success(resp);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出生产报工 Excel")
    @PreAuthorize("@ss.hasPermission('mes:report:export')")
    @OperateLog(type = EXPORT)
    public void exportReportExcel(@Valid ReportExportReqVO exportReqVO,
              HttpServletResponse response) throws IOException {
        List<ReportDO> list = reportService.getReportList(exportReqVO);
        // 导出 Excel
        List<ReportExcelVO> datas = ReportConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "生产报工.xls", "数据", ReportExcelVO.class, datas);
    }

}
